/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.sd.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.entity.Extend;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.sd.common.constants.GlobalEnum;
import com.jeesite.modules.sd.entity.DocRecv;
import com.jeesite.modules.sd.service.DocRecvService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.web.user.EmpUserController;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sd.entity.DocDeliverRecord;
import com.jeesite.modules.sd.service.DocDeliverRecordService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 文件复制Controller
 * 等待领文列表
 *
 * @author ysj
 * @version 2020-07-01
 */
@Controller
@RequestMapping(value = "${adminPath}/sd/docDeliverWaitTake")
public class DocDeliverWaitTakeController extends BaseController {

    @Autowired
    private DocDeliverRecordService recordService;
    @Autowired
    private DocRecvService docRecvService;

    @Autowired
    private OfficeService officeService;
    @Autowired
    private EmpUserController empUserController;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private UserService userService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public DocDeliverRecord get(String id, boolean isNewRecord) {
        return recordService.get(id, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("sd:docDeliverWaitTake:view")
    @RequestMapping(value = {"list", ""})
    public String list(DocDeliverRecord docDeliverRecord, Model model) {

        model.addAttribute("docDeliverRecord", docDeliverRecord);
        return "modules/sd/docDeliverWaitTakeList";
    }

    /**
     * 返回送文单位未领文的文件
     * da 返回的机构数组
     *
     * @return
     */
    @RequiresPermissions("sd:docDeliverWaitTake:view")
    @RequestMapping(value = {"selectFileByUnits", ""})
    @ResponseBody
    public String selectFileByUnits(String[] untis) {
        if (untis == null) {
            return "";
        }
        DocDeliverRecord deliverRecord = new DocDeliverRecord();
        List<DocDeliverRecord> list = new ArrayList<>();
        List<DocDeliverRecord> list1;
        if (untis.length == 0) {
            return renderResult(Global.FALSE, text("请选择送文单位"));
        }
        for (int i = 0; i < untis.length; i++) {
            deliverRecord.setRecvUnitCode(untis[i]);
            deliverRecord.getSqlMap().getWhere().and("take_date", QueryType.IS_NULL, null);
            deliverRecord.getSqlMap().getWhere().and("return_date", QueryType.IS_NULL, null);
            list1 = recordService.findList(deliverRecord);
            if (CollectionUtils.isNotEmpty(list1)) {
                list.addAll(list1);
                list1.clear();
            }
        }
        if (CollectionUtils.isEmpty(list)) {
            return renderResult(Global.FALSE, text("没有文件可送"));
        }

        return renderResult(Global.TRUE, text("请核对文件信息"), list);
    }
    /**
     * 送文单位查询出文件
     * @return
     */

  /*  @RequiresPermissions("sd:docDeliverWaitTake:view")
    @RequestMapping(value = {"searchFiles", ""})
    public String searchFiles(Model model) {
        model.addAttribute("police","");
        model.addAttribute("userName","");
        model.addAttribute("userCode","");
        return "modules/sd/docSendFile";
    }
*/

    /**
     * 等待领文首页
     *
     * @param docDeliverRecord
     * @param model
     * @return
     */
    @RequiresPermissions("sd:docDeliverWaitTake:view")
    @RequestMapping(value = {"index", ""})
    public String index(DocDeliverRecord docDeliverRecord, Model model) {

        model.addAttribute("docDeliverRecord", docDeliverRecord);
        return "modules/sd/docDeliverWaitTakeIndex";
    }

    /**
     * 跳转到拍照页面
     *
     * @return
     */
    @RequestMapping(value = {"takePicture", ""})
    public String takePicture() {


        return "modules/sd/docDeliverTakePicture";
    }

    /**
     * 跳转领文页面
     *
     * @param docDeliverRecord
     * @param model
     * @return
     */
    @RequestMapping(value = {"viewDoc", ""})
    public String viewDoc(DocDeliverRecord docDeliverRecord, Model model) {


        return "modules/sd/docDeliverTakeFile";
        // return "modules/sd/show";
    }


    /**
     * 跳转到送文界面
     */
    @RequestMapping(value = {"sendDoc", ""})
    public String sendDoc(DocDeliverRecord docDeliverRecord, Model model) {

        String officeCode = recordService.getSecretariatOfficeCode(GlobalEnum.OFFICE_TYPE_SECRETARIAT.getKey());
        EmpUser empUser = new EmpUser();
        empUser.setCodes(new String[]{officeCode});
        List<EmpUser> userListByOfficeCodes = empUserService.findUserListByOfficeCodes(empUser);
        if (CollectionUtils.isNotEmpty(userListByOfficeCodes)) {
            String userCode = userListByOfficeCodes.get(0).getUserCode();
            User user = userService.get(userCode);
            String police = user.getExtend().getExtendS1();
            String userName = user.getUserName();
            model.addAttribute("police", police);
            model.addAttribute("userName", userName);
            model.addAttribute("userCode", userCode);
        }
        return "modules/sd/docSendFile";

    }

    /**
     * 批量拟办页面
     *
     * @param docDeliverRecord
     * @param model
     * @return
     */
    @RequiresPermissions("sd:docDeliverWaitTake:edit")
    @RequestMapping(value = {"batchFile", ""})
    public String batchFile(DocDeliverRecord docDeliverRecord, Model model) {
        EmpUser empUser=new EmpUser();
        List<EmpUser> userListByOfficeCodes;
        Office office=new Office();
        Extend extend=new Extend();
        extend.setExtendS1(GlobalEnum.OFFICE_TYPE_PROPOSED.getKey());
        office.setExtend(extend);
        List<Office> list = officeService.findList(office);
       if(CollectionUtils.isEmpty(list)){
           throw new  RuntimeException("没有拟办单位");
       }else{
           String officeCode = list.get(0).getOfficeCode();
           empUser.setCodes(new String[]{officeCode});
           userListByOfficeCodes = empUserService.findUserListByOfficeCodes(empUser);
       }
       if (CollectionUtils.isEmpty(userListByOfficeCodes)){
            throw new  RuntimeException("拟办单位没有人");
       }else{
           String userCode = userListByOfficeCodes.get(0).getUserCode();
           User user = userService.get(userCode);


           model.addAttribute("userName",  user.getUserName());
           model.addAttribute("police", user.getExtend().getExtendS1());
           model.addAttribute("userCode",  userCode);
       }
        return "modules/sd/docDeliverTakeFilePerson";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("sd:docDeliverWaitTake:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<DocDeliverRecord> listData(DocDeliverRecord docDeliverRecord, HttpServletRequest request, HttpServletResponse response) {
        docDeliverRecord.setPage(new Page<>(request, response));
        docDeliverRecord.setDeliverType(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey());
        docDeliverRecord.getSqlMap().getWhere().andBracket("deliver_type", QueryType.EQ, GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey(), 1).or("deliver_type", QueryType.EQ, GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey(), 2).endBracket();
        docDeliverRecord.getSqlMap().getWhere().and("take_date", QueryType.IS_NULL, null);
        Page<DocDeliverRecord> page = recordService.findPage(docDeliverRecord);
        return page;
    }

    /**
     * 送文单位领取文件
     */
    @RequiresPermissions("sd:docDeliverWaitTake:edit")
    @RequestMapping(value = "takefile")
    @ResponseBody
    public String takefile(String[] officeCode, String face, String userName, String police, String userCode) {
        if (StringUtils.isNotEmpty(userCode)) {
            //正常领文
            DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
            for (int i = 0; i < officeCode.length; i++) {
                try {
                    recordService.takeDoc(officeCode[i], userCode);
                } catch (Exception e) {
                    return renderResult(Global.FALSE, text("领取失败"));
                }
            }

        } else {
            //临时领文
            for (int i = 0; i < officeCode.length; i++) {
                try {
                    recordService.takeDoc(officeCode[i], userName, police, "", userCode);
                } catch (Exception e) {
                    return renderResult(Global.FALSE, text("领取失败"));
                }

            }

        }

        return renderResult(Global.TRUE, text("领取成功"));
    }


    /**
     * @param excludeCode
     * @param parentCode
     * @param isAll
     * @param officeTypes
     * @param companyCode
     * @param isShowCode
     * @param isShowFullName
     * @param isLoadUser
     * @param postCode
     * @param roleCode
     * @param ctrlPermi
     * @return
     */
    @RequestMapping({"treeData"})
    @ResponseBody
    public List<Map<String, Object>> treeData(String excludeCode, String parentCode, Boolean isAll, String officeTypes, String companyCode, String isShowCode, String isShowFullName, String isLoadUser, String postCode, String roleCode, String ctrlPermi) {
        List<Map<String, Object>> mapList = ListUtils.newArrayList();
        Office where = new Office();
        where.setStatus("0");
        where.getSqlMap().getWhere().andBracket("extend_s1", QueryType.EQ, GlobalEnum.OFFICE_TYPE_GET.getKey(), 1).or("extend_s1", QueryType.EQ, GlobalEnum.OFFICE_TYPE_SEND.getKey(), 2).endBracket();
        where.setCompanyCode(companyCode);
        if (isAll == null || !isAll || Global.isStrictMode()) {
            this.officeService.addDataScopeFilter(where, ctrlPermi);
        }

        if (StringUtils.isNotBlank(parentCode)) {
            where.setParentCode(parentCode);
            where.setParentCodes("," + parentCode + ",");
        }

        if (StringUtils.isNotBlank(officeTypes)) {
            where.setOfficeType_in(officeTypes.split(","));
        }

        List<Office> list = this.officeService.findList(where);

        for (int i = 0; i < list.size(); ++i) {
            Office e = (Office) list.get(i);
            if ("0".equals(e.getStatus()) && (!StringUtils.isNotBlank(excludeCode) || !e.getId().equals(excludeCode) && !e.getParentCodes().contains("," + excludeCode + ","))) {
                Map<String, Object> map = MapUtils.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentCode());
                String name = e.getOfficeName();
                if ("true".equals(isShowFullName) || "1".equals(isShowFullName)) {
                    name = e.getFullName();
                }

                map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getViewCode(), name));
                map.put("title", e.getFullName());
                if (StringUtils.inString(isLoadUser, new String[]{"true", "lazy"})) {
                    map.put("isParent", true);
                    if (StringUtils.equals(isLoadUser, "true")) {
                        List<Map<String, Object>> userList = this.empUserController.treeData("u_", e.getOfficeCode(), e.getOfficeCode(), companyCode, postCode, roleCode, isAll, isShowCode, ctrlPermi);
                        mapList.addAll(userList);
                    }
                }

                mapList.add(map);
            }
        }

        if (StringUtils.inString(isLoadUser, new String[]{"lazy"}) && StringUtils.isNotBlank(parentCode)) {
            List<Map<String, Object>> userList = this.empUserController.treeData("u_", parentCode, parentCode, companyCode, postCode, roleCode, isAll, isShowCode, ctrlPermi);
            mapList.addAll(userList);
        }

        return mapList;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("sd:docDeliverWaitTake:view")
    @RequestMapping(value = "form")
    public String form(DocDeliverRecord docDeliverRecord, Model model) {
        String str = docDeliverRecord.getDocRecv().getId();
        DocRecv docRecv = docRecvService.get(str);

        model.addAttribute("docRecv", docRecv);
        return "modules/sd/docDeliverHistoryShow";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("sd:docDeliverWaitTake:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated DocDeliverRecord docDeliverRecord) {
        recordService.save(docDeliverRecord);
        return renderResult(Global.TRUE, text("保存文件分发成功！"));
    }

}